package com.ktwlsoft.archivemanage.domain.business.businessService;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.CaseFormat;
import com.ktwlsoft.archivemanage.config.exception.ResultException;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.*;
import com.ktwlsoft.archivemanage.domain.dao.entity.*;
import com.ktwlsoft.archivemanage.domain.dao.entity.view.ReportArchieveTypesStatistic;
import com.ktwlsoft.archivemanage.domain.dao.entity.view.UnitArchiveReport;
import com.ktwlsoft.archivemanage.domain.dao.repository.view.ReportArchieveTypesStatisticMapper;
import com.ktwlsoft.archivemanage.domain.dao.repository.view.UnitArchiveReportMapper;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.payload.basic.*;
import com.ktwlsoft.archivemanage.payload.operationLog.SaveLogRequest;
import com.ktwlsoft.archivemanage.payload.unitArchive.*;
import com.ktwlsoft.archivemanage.payload.unitArchive.request.UnitArchiveManageCompare;
import com.ktwlsoft.archivemanage.payload.unitArchive.request.UnitArchivesCompare;
import com.ktwlsoft.archivemanage.payload.unitArchiveManage.Archive;
import com.ktwlsoft.archivemanage.payload.unitArchiveManage.ArchiveUnitStatics;
import com.ktwlsoft.archivemanage.service.security.UserPrincipal;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.Year;
import java.util.*;

/**
 * @author chenkun
 * @version 1.0
 * @description 室藏档案管理业务层服务类
 * @date 2019-10-29
 */
@Service
public class UnitArchiveManageBusinessService {

    @Autowired
    private UnitArchiveManageRepositoryService unitArchiveManageRepositoryService;

    @Autowired
    private UnitArchivesRepositoryService unitArchivesRepositoryService;

    @Autowired
    private AnnualReportRepositoryService annualReportRepositoryService;

    @Autowired
    private UnitArchiveReportMapper unitReportMapper;

    @Autowired
    private ReportArchieveTypesStatisticMapper reportStatisticMapper;

    @Autowired
    private ArchiveUnitRepositoryService archiveUnitRepositoryService;

    /**
     * @param request
     * @return Result
     * @description 增加室藏档案管理信息
     */
    @Transactional(rollbackFor = Exception.class)
    public Result addUnitArchiveManage(UnitArchiveManageAddRequest request) {
        //SimpleDateFormat sdf=new SimpleDateFormat("yyyy");
        Long unitId = request.getUnitId();
        List<UnitArchivesAddRequest> archiveTypesList = request.getArchiveTypesList();
        UnitArchiveManage unitArchiveManage = new UnitArchiveManage();
        Map<String, Object> data = new HashMap<String, Object>();
        try {
            //writeDate=sdf.parse(request.getWriteDate());
            data.put("unitId", request.getUnitId());
            data.put("selectedYear", request.getWriteDate());
            Map<String, Object> resultMap = unitArchiveManageRepositoryService.findUnitArchiveManageInfo(data);
            if (resultMap != null) {
                data.put("businessId", resultMap.get("archiveManageId"));
                List<Map<String, Object>> unitArchivesList = unitArchivesRepositoryService.findUnitArchivesList(data);
                if (unitArchivesList != null && unitArchivesList.size() > 0) {
                    return Result.body(request.getWriteDate(), ResultType.BUSINESS_ERROR).withMessage("当前年度已添加室藏档案数据");
                }
            }
            /**添加室藏档案管理信息**/
            BeanUtils.copyProperties(request, unitArchiveManage);
            //No matter if annual report exists, this should be valid
            unitArchiveManage.setValid(true);
            unitArchiveManage.setCompareConfirm(false);
            //unitArchiveManage.setWriteDate(request.getWriteDate());
            Account account = UserPrincipal.getCurrentUser();
            unitArchiveManage.setWritter(account.getRealName());
            unitArchiveManage.setWritterId(account.getId());
            // find annual report
            if(annualReportRepositoryService.existByUnitIdYear(unitArchiveManage.getUnitId(), unitArchiveManage.getWriteDate())){
                annualReportRepositoryService.setInvalidByUnitIdAndYear(unitArchiveManage.getUnitId(), unitArchiveManage.getWriteDate());
            }
            unitArchiveManageRepositoryService.addUnitArchiveManage(unitArchiveManage);
            /**批量增加室藏档案信息**/
            for (UnitArchivesAddRequest unitArchivesAddRequest : archiveTypesList) {
                UnitArchives unitArchives = new UnitArchives();
                BeanUtils.copyProperties(unitArchivesAddRequest, unitArchives);
                unitArchives.setBusinessId(unitArchiveManage.getId());
                unitArchives.setBusinessFrom("manual");
                unitArchives.setUnitId(unitId);
                unitArchivesRepositoryService.addUnitArchives(unitArchives);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ResultException(ResultType.SAVING_ERROR.getReason(),ResultType.SAVING_ERROR);
        }
        return Result.ok(unitArchiveManage.getId());
    }

    /**
     * @param data
     * @return Result
     * @description 删除室藏档案管理
     */
    @Transactional(rollbackFor = Exception.class)
    public Result deleteUnitArchiveManage(Map<String, Object> data) {
        Long businessId = (Long) data.get("businessId");
        Long unitId = (Long) data.get("unitId");
        Year year = (Year) data.get("year");
        if (businessId == null) {
            return Result.body(null, ResultType.BUSINESS_ERROR).withMessage("室藏档案管理信息不存在");
        }
        try {
            unitArchiveManageRepositoryService.deleteUnitArchiveManage(businessId);
            unitArchivesRepositoryService.deleteUnitArchives(businessId);
            //check report if exist
            if(annualReportRepositoryService.existByUnitIdYear(unitId,year)){
                annualReportRepositoryService.setValideByUnitIdAndYear(unitId,year);
                annualReportRepositoryService.setCompareConfirm(unitId, year, false);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new ResultException(ResultType.DELETE_ERROR.getReason(),ResultType.DELETE_ERROR);
        }
        return Result.body(businessId, ResultType.BUSINESS_SUCCESS).withMessage("室藏档案管理删除成功");
    }

    /**
     * @param request
     * @return Result
     * @description 编辑室藏档案管理信息
     */
    @Transactional
    public Result updateUnitArchiveManage(UnitArchiveManageUpdateRequest request) {
        Long businessId = request.getBusinessId();
        String businessFrom = request.getBusinessFrom();
        List<UnitArchivesUpdateRequest> archiveTypeList = request.getArchiveTypesList();
        if (businessId == null) {
            return Result.body(null, ResultType.BUSINESS_ERROR).withMessage("室藏档案管理信息不存在");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        try {
            //Date writeDate=sdf.parse(request.getWriteDate());
            if ("manual".equals(businessFrom)) {
                UnitArchiveManage unitArchiveManage = new UnitArchiveManage();
                unitArchiveManage.setId(businessId);
                unitArchiveManage.setWriteDate(request.getWriteDate());
                unitArchiveManageRepositoryService.updateUnitArchiveManage(unitArchiveManage);
            }
            if ("report".equals(businessFrom)) {
                Report report = new Report();
                report.setId(businessId);
                report.setWriteDate(request.getWriteDate());
                annualReportRepositoryService.updateAnnualReportInfo(report);
            }
            if (archiveTypeList != null && archiveTypeList.size() > 0) {
                /**批量修改室藏档案信息**/
                for (UnitArchivesUpdateRequest item : archiveTypeList) {
                    UnitArchives unitArchives = new UnitArchives();
                    BeanUtils.copyProperties(item, unitArchives);
                    unitArchives.setId(item.getArchiveId());
                    unitArchivesRepositoryService.updateUnitArchives(unitArchives);
                }
            } else {
                Result.body(null, ResultType.BUSINESS_ERROR).withMessage("室藏档案信息不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ResultException(ResultType.UPDATE_ERROR.getReason(),ResultType.UPDATE_ERROR);
        }
        return Result.body(businessId, ResultType.BUSINESS_SUCCESS).withMessage("室藏档案管理更新成功");
    }

    /**
     * @param request
     * @return Result
     * @description 同年数据比较
     */
    public Result compareSameYearData(UnitArchiveManageCompareRequest request) {
        int manualTotal = 0;
        int reportTotal = 0;
        Map<String, Integer> totalMap = new HashMap<String, Integer>();
        UnitArchiveManageCompare manualUnitArchiveManage = request.getMunualUnitArchiveManage();
        UnitArchiveManageCompare reportUnitArchiveManage = request.getReportUnitArchiveManage();
        if (manualUnitArchiveManage.getWriteDate().compareTo(reportUnitArchiveManage.getWriteDate()) != 0) {
            return Result.body(null, ResultType.BUSINESS_ERROR).withMessage("所选数据不在同一年");
        }
        List<UnitArchivesCompare> manualUnitArchives = request.getManualUnitArchives();
        List<UnitArchivesCompare> reportUnitArchives = request.getReportUnitArchives();
        /**统计手动添加各类档案总数**/
        if (manualUnitArchives != null && manualUnitArchives.size() > 0) {
            for (UnitArchivesCompare manualUnitArchive : manualUnitArchives) {
                reportTotal += manualUnitArchive.getTenYear();
                reportTotal += manualUnitArchive.getThirtyYear();
                reportTotal += manualUnitArchive.getForever();
            }
        }
        /**统计年度报送各类档案总数**/
        if (reportUnitArchives != null && reportUnitArchives.size() > 0) {
            for (UnitArchivesCompare reportUnitArchive : reportUnitArchives) {
                manualTotal += reportUnitArchive.getTenYear();
                manualTotal += reportUnitArchive.getThirtyYear();
                manualTotal += reportUnitArchive.getForever();
            }
        }
        totalMap.put("manualTotal", manualTotal);
        totalMap.put("reportTotal", reportTotal);
        return Result.body(totalMap, ResultType.BUSINESS_SUCCESS);
    }

    /**
     * @param request
     * @return Result
     * @description 同年数据对比确认
     */
    public Result compareConfirm(CompareConfirmRequest request) {
        Long manualId = request.getManualId();
        Long reportId = request.getReportId();
        if (manualId == null || reportId == null) {
            return Result.body(null, ResultType.BUSINESS_ERROR).withMessage("所选数据不存在");
        }
        String selectedBusinessFrom = request.getSelectedBusinessFrom();
        try {
            /**若确认选择手动添加数据，则更新手动添加数据为已对比状态**/
            if ("manual".equals(selectedBusinessFrom)) {
                UnitArchiveManage unitArchiveManage = new UnitArchiveManage();
                unitArchiveManage.setCompareConfirm(true);
                unitArchiveManage.setId(manualId);
                unitArchiveManage.setValid(true);
                unitArchiveManageRepositoryService.updateCompareConfirm(unitArchiveManage);
                Report report = new Report();
                report.setCompareConfirm(false);
                report.setId(reportId);
                report.setValid(false);
                annualReportRepositoryService.updateAnnualReportInfo(report);
            } else if ("report".equals(selectedBusinessFrom)) {
                /**若确认选择年度报送数据，则更新手动添加数据为已对比状态**/
                Report report = new Report();
                report.setCompareConfirm(true);
                report.setId(reportId);
                report.setValid(true);
                annualReportRepositoryService.updateAnnualReportInfo(report);
                UnitArchiveManage unitArchiveManage = new UnitArchiveManage();
                unitArchiveManage.setCompareConfirm(false);
                unitArchiveManage.setId(manualId);
                unitArchiveManage.setValid(false);
                unitArchiveManageRepositoryService.updateCompareConfirm(unitArchiveManage);
            }else{
                return Result.body(null, ResultType.BUSINESS_ERROR).withMessage("未能找到正确的业务来源，请核对！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.body(null, ResultType.BUSINESS_ERROR).withMessage(e.getMessage());
        }
        return Result.ok(null).withMessage("同年数据对比成功");

    }

    @Transactional(rollbackFor = Exception.class)
    public ArchiveUnitStatics findUnitStatics(Long unitId) {
        ArchiveUnitStatics archiveUnitStatics = unitArchiveManageRepositoryService.findUnitStatics(unitId);
        if(archiveUnitStatics == null) {
            return null;
        }
        List<Archive> archives = unitArchiveManageRepositoryService.findUnitArchiveTypesStatistic(unitId);
        archiveUnitStatics.setArchives(archives);
        ArchiveUnit unit = archiveUnitRepositoryService.getById(unitId);
        OperationRepositoryService.saveLog(new SaveLogRequest(
                OperationLog.OperationType.CHECK,
                "查看室藏档案《" + unit.getUnitName() + "》",
                "室藏档案",
                OperationLog.BusinessType.BUSINESS
        ));
        return archiveUnitStatics;
    }

    @Transactional(rollbackFor = Exception.class)
    public PageInfo<UnitArchiveReport> findUnitArchieveByYear(Integer pn, Integer pageSize, Long unitId, String field, String order) {
        field = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, field);
        PageHelper.startPage(pn,pageSize);
        List<UnitArchiveReport> reports = unitReportMapper.selectAll(unitId, field, order);
        for (UnitArchiveReport report :
                reports) {
            List<ReportArchieveTypesStatistic> reportStatistics = reportStatisticMapper.selectAll(report.getId());
            report.setStatistics(reportStatistics);
        }
        return new PageInfo<>(reports);
    };
}
